package com.tanhua.service;

import com.oss.OssTemplate;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.UserInfoAPI;
import com.tanhua.dubbo.mongo.CommentAPI;
import com.tanhua.dubbo.mongo.MovementAPI;
import com.tanhua.exception.MyException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.mongo.Comment;
import com.tanhua.mongo.Movement;
import com.tanhua.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class MovementService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private MovementAPI movementAPI;

    @DubboReference
    private UserInfoAPI userInfoAPI;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private CommentAPI commentAPI;

    public void publishMovements(MovementVo movementVo, MultipartFile[] imageContent) {
        //1 上传图片到阿里云
        List<String> medias = new ArrayList<>();
        if (imageContent.length!=0){
//            Arrays.stream(imageContent).forEach(img -> {
//                try {
//                    String url = ossTemplate.upload(img.getOriginalFilename(), img.getInputStream());
//                    medias.add(url);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
            for (MultipartFile mf:imageContent){
                try {
                    String url = ossTemplate.upload(mf.getOriginalFilename(), mf.getInputStream());
                    medias.add(url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        //2 图片地址保存到vo中
        movementVo.setMedias(medias);

        //3 远程调用dubbo-mongo，保存数据
        movementAPI.publishMovements(movementVo, UserHolder.getUserId());
    }

    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //1  根据userId去mongoDB中分页查找动态信息
        PageResult pr = movementAPI.findByUserId(userId,page,pagesize);
        //2  组装返回结果--适当的封装修改
        List<Movement> items = (List<Movement>) pr.getItems();
        if (items!=null&&items.size()>0){
            //根据当前登录的用户id查找用户信息
            UserInfo userInfo = userInfoAPI.findById(items.get(0).getUserId());
            List<DongTaiVo> dtvoList = new ArrayList<>();
            //遍历items集合
            for (Movement movement:items){
                DongTaiVo dongTaiVo = new DongTaiVo();
                BeanUtils.copyProperties(userInfo,dongTaiVo);
                BeanUtils.copyProperties(movement,dongTaiVo);

                if (StringUtils.isNotBlank(userInfo.getTags())){
                    dongTaiVo.setTags(userInfo.getTags().split(","));
                }
                if (movement.getMedias().size()!=0){
                    String[] images = new String[movement.getMedias().size()];
                    for (int i=0;i<movement.getMedias().size();i++){
                        images[i] = movement.getMedias().get(i);
                    }
                    dongTaiVo.setImageContent(images);
                }
                //距离
                dongTaiVo.setDistance("500m");
                //时间
                Date date = new Date(movement.getCreated());
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                dongTaiVo.setCreateDate(format);
                //是否已喜欢
                dongTaiVo.setHasLiked(0);
                dongTaiVo.setHasLoved(0);

                dongTaiVo.setId(movement.getId().toHexString());

                dtvoList.add(dongTaiVo);
            }
            //替换pr中的items
            pr.setItems(dtvoList);
        }



        return pr;
    }

    public PageResult findByFriendId(Integer page, Integer pagesize) {
        //1 去mongodb中查找动态信息
        PageResult pr= movementAPI.findByFriendId(UserHolder.getUserId(),page,pagesize);
        //2 封装结果
        List<Movement> items = (List<Movement>) pr.getItems();
        if (items!=null&&items.size()>0){

            List<DongTaiVo> dtvoList = new ArrayList<>();
            //遍历items集合
            for (Movement movement:items){
                //根据当前登录的用户id查找用户信息
                UserInfo userInfo = userInfoAPI.findById(movement.getUserId());
                DongTaiVo dongTaiVo = new DongTaiVo();
                BeanUtils.copyProperties(userInfo,dongTaiVo);
                BeanUtils.copyProperties(movement,dongTaiVo);

                if (StringUtils.isNotBlank(userInfo.getTags())){
                    dongTaiVo.setTags(userInfo.getTags().split(","));
                }
                if (movement.getMedias().size()!=0){
                    String[] images = new String[movement.getMedias().size()];
                    for (int i=0;i<movement.getMedias().size();i++){
                        images[i] = movement.getMedias().get(i);
                    }
                    dongTaiVo.setImageContent(images);
                }
                //距离
                dongTaiVo.setDistance("500m");
                //时间
                Date date = new Date(movement.getCreated());
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                dongTaiVo.setCreateDate(format);
                //是否已喜欢
                dongTaiVo.setHasLiked(0);
                dongTaiVo.setHasLoved(0);

                dongTaiVo.setId(movement.getId().toHexString());

                dtvoList.add(dongTaiVo);
            }
            //替换pr中的items
            pr.setItems(dtvoList);
        }



        return pr;
    }

    public PageResult recommend(Integer page, Integer pagesize) {
        //1 根据用户的id去redis中查找数据,如果找到了，就进行分页查找
        String recommend_userId = stringRedisTemplate.opsForValue().get("MOVEMENTS_RECOMMEND_" + UserHolder.getUserId());
        if(StringUtils.isNotBlank(recommend_userId)){
            //分页查找
            String[] split = recommend_userId.split(",");
            int startIndex = (page-1)*pagesize;
            int endIndex = startIndex + pagesize - 1;

            //判断是否已经超过可查的条数
            if (startIndex>=recommend_userId.length()){
                int lastPage = recommend_userId.length()%pagesize==0? recommend_userId.length()/pagesize : (recommend_userId.length()/pagesize +1 );

//                throw new MyException(ErrorResult.error());
                startIndex = (lastPage-1)*pagesize;
                endIndex = startIndex + pagesize - 1;
            }
            ArrayList<Long> list = new ArrayList<>();
            for (int i=startIndex;i<=endIndex;i++){
                list.add(Long.valueOf(split[i]));
            }
            //调用Movement_API
            List<Movement> items = movementAPI.findByPIds(list);
            //对结果进行封装处理
            PageResult pr = new PageResult();
            pr.setCounts(split.length);
            pr.setPage(page);
            pr.setPagesize(pagesize);
            pr.setPages(recommend_userId.length()%pagesize==0? recommend_userId.length()/pagesize : (recommend_userId.length()/pagesize +1 ));

            fengZhuangMovement(pr,items);

            return pr;
        }else {
            //2 如果没有找到，就随机pagesize条
            List<Movement> items = movementAPI.randomTuijian(pagesize);
            //对结果进行封装处理
            PageResult pr = new PageResult();
            pr.setCounts(200);
            pr.setPage(page);
            pr.setPagesize(pagesize);
            pr.setPages(20);
            fengZhuangMovement(pr,items);
            return pr;
        }

    }

    private void fengZhuangMovement(PageResult pr,List<Movement> items){
        //
        if (items!=null&&items.size()>0){

            List<DongTaiVo> dtvoList = new ArrayList<>();
            //遍历items集合
            for (Movement movement:items){
                //根据当前登录的用户id查找用户信息
                UserInfo userInfo = userInfoAPI.findById(movement.getUserId());
                DongTaiVo dongTaiVo = new DongTaiVo();
                BeanUtils.copyProperties(userInfo,dongTaiVo);
                BeanUtils.copyProperties(movement,dongTaiVo);
                dongTaiVo.setId(movement.getId().toHexString());

                if (StringUtils.isNotBlank(userInfo.getTags())){
                    dongTaiVo.setTags(userInfo.getTags().split(","));
                }
                if (movement.getMedias().size()!=0){
                    String[] images = new String[movement.getMedias().size()];
                    for (int i=0;i<movement.getMedias().size();i++){
                        images[i] = movement.getMedias().get(i);
                    }
                    dongTaiVo.setImageContent(images);
                }
                //距离
                dongTaiVo.setDistance("500m");
                //时间
                Date date = new Date(movement.getCreated());
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                dongTaiVo.setCreateDate(format);
                //是否已喜欢
                dongTaiVo.setHasLiked(0);
                dongTaiVo.setHasLoved(0);



                dtvoList.add(dongTaiVo);
            }
            //替换pr中的items
            pr.setItems(dtvoList);
        }
    }

    public Integer like(String movementId) {
        //1 查询是否已经点赞，
        boolean hasComment = movementAPI.hasComment(movementId,UserHolder.getUserId(), CommentType.LIKE);
        //2 如果已经点赞，直接抛出异常
        if (hasComment){
            throw new MyException(ErrorResult.error());
        }
        //3 如果没有点赞，查无此数据，就保存到mongoDB中
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE);
        comment.setUserId(UserHolder.getUserId());
        Movement movement = movementAPI.findByMovementId(movementId);
        if (movement!=null) {
            comment.setPublishUserId(movement.getUserId());
        }
        comment.setCreated(System.currentTimeMillis());
        Integer count  = commentAPI.save(comment);

        return count;
    }

    public Integer dislike(String movementId) {
        //1 查询是否已经点赞
        boolean hasComment = movementAPI.hasComment(movementId,UserHolder.getUserId(), CommentType.LIKE);
        //2 如果没有点赞，直接抛出异常
        if (hasComment){
            throw new MyException(ErrorResult.error());
        }

        //3 如果已经点赞，删除数据，并返回新的点赞数
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(CommentType.LIKE);

        Integer count = commentAPI.delete(comment);
        return count;
    }

    public DongTaiVo findByMovementId(String movementId) {
        // 1 根据movementId查找movement信息
        Movement movement = movementAPI.findByMovementId(movementId);
        //2 根据movement中的userId查找UserInfo信息
        if (movement==null){
            return null;
        }
        UserInfo userInfo = userInfoAPI.findById(movement.getUserId());
        //3 封装信息
        DongTaiVo dongTaiVo = new DongTaiVo();
        BeanUtils.copyProperties(movement,dongTaiVo);
        BeanUtils.copyProperties(userInfo,dongTaiVo);
        dongTaiVo.setId(movement.getId().toHexString());

        if (StringUtils.isNotBlank(userInfo.getTags())){
            dongTaiVo.setTags(userInfo.getTags().split(","));
        }
        if (movement.getMedias().size()!=0){
            String[] images = new String[movement.getMedias().size()];
            for (int i=0;i<movement.getMedias().size();i++){
                images[i] = movement.getMedias().get(i);
            }
            dongTaiVo.setImageContent(images);
        }
        //距离
        dongTaiVo.setDistance("500m");
        //时间
        Date date = new Date(movement.getCreated());
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        dongTaiVo.setCreateDate(format);
        //是否已喜欢
        dongTaiVo.setHasLiked(0);
        dongTaiVo.setHasLoved(0);



        //4 返回
        return dongTaiVo;

    }
}
